package Set;

import java.util.*;

public class TestSet {
    public static void main(String[] args) {
        outputOnce();
    }

    //    利用Set可以去除重复元素；
//
//    遍历SortedSet按照元素的排序顺序遍历，也可以自定义排序算法。
    private static void outputOnce() {
        List<Message> received = List.of(
                new Message(1, "Hello!"),
                new Message(2, "发工资了吗？"),
                new Message(2, "发工资了吗？"),
                new Message(3, "去哪吃饭？"),
                new Message(3, "去哪吃饭？"),
                new Message(4, "Bye")
        );
        List<Message> displayMessages = process(received);
        for (Message message : displayMessages) {
            System.out.println(message.sequence + " : " + message.text);
        }
    }

    static List<Message> process(List<Message> received) {
//        List<Message> messages = new ArrayList<>();
        // TODO: 按sequence去除重复消息
//        HashSet<Integer> hashSet = new HashSet<Integer>();
//        for (Message message:received) {
//            if (!hashSet.contains(message.sequence)) {
//                hashSet.add(message.sequence);
//                messages.add(message);
//            }
//        }
        // set 天然只能有一个key，消息需要排序
        TreeSet<Message> setReceived = new TreeSet<>((p1, p2) ->{
            //                Integer.compare(p1.sequence, p2.sequence)
            return p1.sequence - p2.sequence;
        }

        );

        setReceived.addAll(received);

        return new ArrayList<>(setReceived);
    }

    private static class Message {
        public final int sequence;
        public final String text;

        public Message(int sequence, String text) {
            this.sequence = sequence;
            this.text = text;
        }
    }
}
